package com.star.spring.easyexcel.listener;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

@Slf4j
public class ImageExcelListener<T> extends AnalysisEventListener<T> {
    
    private final List<T> dataList = new ArrayList<>();
    private final Map<String, byte[]> imageMap = new HashMap<>();
    private final String imageSavePath;
    
    public ImageExcelListener(String imageSavePath) {
        this.imageSavePath = imageSavePath;
    }
    
    @Override
    public void invoke(T data, AnalysisContext context) {
        dataList.add(data);
    }
    
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！共解析 {} 条数据", dataList.size());
        // 保存所有图片到文件系统
        saveAllImages();
    }
    
    private void saveAllImages() {
        for (Map.Entry<String, byte[]> entry : imageMap.entrySet()) {
            saveImageToFile(entry.getValue(), entry.getKey());
        }
    }
    
    private void saveImageToFile(byte[] imageData, String imageName) {
        try {
            // 确保目录存在
            Files.createDirectories(Paths.get(imageSavePath));
            
            // 根据图片头信息判断图片格式
            String extension = getImageExtension(imageData);
            
            // 生成文件路径
            String filePath = imageSavePath + "/" + imageName + extension;
            
            // 保存图片到文件系统
            Files.write(Paths.get(filePath), imageData);
            log.info("图片已保存: {}", filePath);
        } catch (IOException e) {
            log.error("保存图片失败: ", e);
        }
    }
    
    private String getImageExtension(byte[] imageData) {
        if (imageData == null || imageData.length < 4) {
            return ".jpg";
        }
        
        // 简单的图片格式检测
        if (imageData[0] == (byte) 0xFF && imageData[1] == (byte) 0xD8) {
            return ".jpg";
        } else if (imageData[0] == (byte) 0x89 && imageData[1] == (byte) 0x50 && 
                   imageData[2] == (byte) 0x4E && imageData[3] == (byte) 0x47) {
            return ".png";
        } else if (imageData[0] == (byte) 0x47 && imageData[1] == (byte) 0x49 && 
                   imageData[2] == (byte) 0x46) {
            return ".gif";
        } else {
            return ".jpg"; // 默认格式
        }
    }
    
    public List<T> getDataList() {
        return dataList;
    }
    
    public Map<String, byte[]> getImageMap() {
        return imageMap;
    }
}